package com.ce.pms.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import com.ce.pms.exception.BusinessException;
import com.ce.pms.house.vo.ImageVO;
import com.ce.util.BlankUtil;

/**
 * 逻辑、功能相关描述: 图片上传组件(此组件必须与validation.js,imageUpload.js同时使用)
 *
 * @author  yandawei 编写日期：2008-7-18
 */
public class ImageUploadTag extends TagSupport {

	/**
	 * 组件名
	 */
	private String name;

	/**
	 * 数据集
	 */
	private Object data;

	/**
	 * 允许上传的文件类型
	 */
	private String imageType;

	/***
	 * 支持的图片类型
	 */
	private static final String ALLOWIMAGETYPE="jpg,gif";

	/**
	 * 后缀名(对应具体的界面属性,如平面图后缀名为image1,后台action找image1对应平面图的图片信息)
	 */
	private String postfixName;

	/**
	 * 上传单个文件的最大值
	 */
	private Integer maxSize = new Integer(500);

	/**
	 * 最大上传文件数
	 */
	private Integer maxNum = new Integer(1);

	/**
	 * 上传目录
	 */
	private String uploadFilePath = "";


	/***
	 * div层开始滚动高度
	 */
	private String divHight = "30";




	/**
	 *  动态生成上传input file
	 *
	 *     <a id="a_trafficImage_add" href="#" class="addfile">
			<input id="trafficImage" class="addfile" type="file" name="picpath1" size="1" title="点击选择附件">
			</a>添加图片
	           <div id="selectFile">
	                 <div class = "inputdiv" id="4000251">
						<a href="#">200807162053409299.xml</a>
						<img height=16 src="/pms2.0/images/ico_delete.gif" width=16 onclick="deleteHide('4000251','selectFile')">
						</div>
	            </div>

            <br>
            <span class="note_word">(支持jpg,gif格式,文件小于500k)</span>
            var cleckInputFile1 = document.getElementById('picpath1');
		    var selectedFile_div1 = document.getElementById('selectFile');
		    initFileInput(cleckInputFile1,selectedFile_div1,1,"Ichnograp");
	 */
	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
		//以后要改
		//String path = request.getContextPath()+"/uploadimages/";
		StringBuffer out = new StringBuffer();
		StringBuffer className = new StringBuffer("");
		String tempImageType = imageType == null?ALLOWIMAGETYPE:imageFilter(imageType);
		if(BlankUtil.isBlank(this.name))
			throw new IllegalArgumentException("name must required!");
		if(BlankUtil.isBlank(this.postfixName))
			throw new IllegalArgumentException("postfixName must required!");
		if(!BlankUtil.isBlank(this.imageType))
		{
			this.imageType = this.imageType.replaceAll(",", "-");
			className.append(" validate-file-"+this.imageType);
		}
		out = buildHead(out,className);
		out.append("<div id='file_container_").append(this.name).append("' style=\"height:").append(divHight).append("px;overflow:auto;\">");

		processData(data,out);

		out.append("<script>");
		out.append("initFileInput(\"file_"+this.name+"_"+this.postfixName+"\",\"file_container_"+this.name+"\","+this.maxNum+",\""+tempImageType+"\",\""+this.postfixName+"\",\""+this.maxSize+"\")");
		out.append("</script>");

		out.append("</div>");

		out.append("<span class=\"note_word\">(支持").append(tempImageType).append("格式,文件小于"+this.maxSize+"K)</span>");
		try {
			pageContext.getOut().write(out.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}


	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}
	/**
	 * 功能描述:  创建<a id="a_trafficImage_trafficImage" href="#" class="addfile">
	 * 					<input id="file_trafficImage_trafficImage" class="addfile" type="file" name="file_trafficImage_trafficImage" size="1" style="width:20px">
	 * 				</a><br>
	 * @param out
	 * @param className
	 * @return
	 * Create author:yandawei<br>
	 * Create on:2008-7-31  <br>
	 * Edit author:  yixianjian<br>
	 * Edit on:   2008-7-31<br>
	 * Why:    代码重构下 <br>
	 */
	private StringBuffer buildHead(StringBuffer out,StringBuffer className){
		out.append("<a id='a_trafficImage_").append(this.name).append("'");
		out.append("  href='#' ");
		out.append("  class='addfile' >");

		String inputId = "file_" + this.name + "_" + this.postfixName;
		String inputName = "file_" + this.name + "_" + this.postfixName;
		out = buildInputFile(out,"file",inputId,inputName,null,className.toString());

		out.append("</a><br>");

		return out;
	}

	/**
	 * 功能描述:  处理传入的data 确定是否生成相应的容器div的子容器<br>
	 * @param data
	 * @param out
	 * Create author:yixianjian <br>
	 * Create on:2008-7-31  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private void processData(Object data,StringBuffer out){
		if(BlankUtil.isBlank(data)) return;

		if(data instanceof java.util.List){//修改初始化为集合时
			List<ImageVO> dataList = (List<ImageVO>) data;
			processDataForList(out,dataList);
		}else if(data instanceof java.util.Set){
			Set<ImageVO> dataSet = (Set<ImageVO>) data;
			processDataForSet(out,dataSet);
		}else if(data instanceof ImageVO){//修改初始化为ImageVO对象时
			ImageVO image = (ImageVO) data;
			processDataForImage(out,image);
		}
		else{
			throw new IllegalArgumentException("data  setAttribute only List<ImageVO> or ImageVO obj");
		}
	}
	/**
	 * 功能描述:  处理传入的data 列表(当data为List时)<br>
	 * @param out
	 * @param dataList
	 * Create author:yixianjian <br>
	 * Create on:2008-7-31  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private void processDataForList(StringBuffer out,List<ImageVO> dataList){
		if(dataList.size()>this.maxNum){
			throw new BusinessException("超过允许上传的最大值");
		}
		out.append("<input type='hidden' name='file_size_").append(this.postfixName).append("' value='").append(dataList.size()).append("'>");
		for(int i = 0 ; i < dataList.size(); i++){
			out.append("<input type=\"hidden\" name=\"id_"+i+"_"+this.postfixName+"\" value=\""+dataList.get(i).getId()+" \">");
			out.append("<div>");
			out.append(" <input type=\"hidden\" name=\"name_"+i+"_"+this.postfixName+" \" value=\""+dataList.get(i).getName()+" \">");
			out.append(" <input type=\"hidden\" name=\"path_"+i+"_"+this.postfixName+" \" value=\""+dataList.get(i).getPath()+" \">");
			out.append(" <a href=\"#\" onclick=\"preview('"+dataList.get(i).getId()+"')\">"+dataList.get(i).getName()+"</a>");
			out.append(" <img  src=\"images/ico_delete.gif\"   border=\"0\" align=\"absbottom\">");
			out.append("</div>");
		}
	}

	/**
	 * 功能描述:  处理传入的data 列表(当data为List时)<br>
	 * @param out
	 * @param dataList
	 * Create author:yixianjian <br>
	 * Create on:2008-7-31  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private void processDataForSet(StringBuffer out,Set<ImageVO> dataSet){

		if(dataSet.size()>this.maxNum){
			throw new BusinessException("超过允许上传的最大值");
		}
		out.append("<input type='hidden' name='file_size_").append(this.postfixName).append("' value='").append(dataSet.size()).append("'>");
        int i=-1;
		for(ImageVO vo :dataSet){
			i++;
			out.append("<input type=\"hidden\" name=\"id_"+i+"_"+this.postfixName+"\" value=\""+vo.getId()+" \">");
			out.append("<div>");
			out.append(" <input type=\"hidden\" name=\"name_"+i+"_"+this.postfixName+" \" value=\""+vo.getName()+" \">");
			out.append(" <input type=\"hidden\" name=\"path_"+i+"_"+this.postfixName+" \" value=\""+vo.getPath()+" \">");
			out.append(" <a href=\"#\" onclick=\"preview('"+vo.getId()+"')\">"+vo.getName()+"</a>");
			out.append(" <img  src=\"images/ico_delete.gif\"   border=\"0\" align=\"absbottom\">");
			out.append("</div>");
		}

	}

	/**
	 * 功能描述:  处理传入的data--当data为单个imageVO时<br>
	 * @param out
	 * @param image
	 * Create author:yixianjian <br>
	 * Create on:2008-7-31  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private void processDataForImage(StringBuffer out,ImageVO image){
		if(!checkImage(image)) return;

		out.append("<input type=\"hidden\" name=\"file_size_"+this.postfixName+" \" value=\"1\">");
		out.append("<input type=\"hidden\" name=\"id_0_"+this.postfixName+"\" value=\""+image.getId()+" \">");
		out.append("<div>");
		out.append(" <input type=\"hidden\" name=\"name_0_"+this.postfixName+" \" value=\""+image.getName()+" \">");
		out.append(" <input type=\"hidden\" name=\"path_0_"+this.postfixName+" \" value=\""+image.getPath()+" \">");
		out.append(" <a href=\"#\" onclick=\"preview('"+image.getId()+"')\">"+image.getName()+"</a>");
		out.append(" <img  src=\"images/ico_delete.gif\"   border=\"0\" align=\"absbottom\">");
		out.append("</div>");
	}

	/**
	 * 功能描述:  初始化页面时，如果设置了Data,则 ImageVO 各值不能为空<br>
	 * @param imageVO
	 * Create author:yixianjian <br>
	 * Create on:2008-7-31  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private boolean checkImage(ImageVO imageVO){
		if(imageVO == null)
			return false;
		if(imageVO.getId() == null)
			return false;
		if(imageVO.getName() == null)
			return false;
		if(imageVO.getPath() == null)
			return false;

		return true;
	}
	/**
	 * 功能描述: 构建一个input<br>
	 * @param out
	 * @param id input id
	 * @param intputType  intpu类型
	 * @param name  input 名称
	 * @param value  input value
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-7-31  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private StringBuffer buildInputFile(StringBuffer out,String intputType,String id,String name,String value,String className){
		out.append("<input type='").append(intputType).append("'");
		out.append(" id='").append(id).append("' ");
		out.append(" name='").append(name).append("' ");
		out.append(" value='").append(value).append("' ");
		out.append(" class='addfile ").append(className).append("' ");
		out.append(" size='1' ");
		out.append(" style=\"width: 20px\"");
		out.append(">");
		return out;
	}

	/***
	 * 功能描述:  过滤多余的图片类型(针对图片类型大小写jpg,JPG)<br>
	 * @param imageType
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-11-18  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private String imageFilter(String imageType){
		String[] array = imageType.toLowerCase().split(",");
		List<String> list = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
	    for(int i =0; i< array.length ; i++){
	       String key = array[i] ;
	       if(list.contains(key)){
	           continue;
	       }
	       list.add(key);
	       sb.append(key).append(",");
	   }
	   return sb.deleteCharAt(sb.length()-1).toString();
	}

	@Override
	public void release() {
		super.release();
		this.data = null;
		this.id = null;
		this.imageType = null;
		this.maxNum = null;
		this.maxSize = null;
		this.name = null;
		this.postfixName = null;
		this.divHight = null;
	}



	public Object getData() {
		return data;
	}


	public void setData(Object data) {
		this.data = data;
	}

	public String getImageType() {
		return imageType;
	}

	public void setImageType(String imageType) {
		this.imageType = imageType;
	}

	public Integer getMaxNum() {
		return maxNum;
	}

	public void setMaxNum(Integer maxNum) {
		this.maxNum = maxNum;
	}

	public Integer getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(Integer maxSize) {
		this.maxSize = maxSize;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPostfixName() {
		return postfixName;
	}

	public void setPostfixName(String postfixName) {
		this.postfixName = postfixName;
	}

	public String getUploadFilePath() {
		return uploadFilePath;
	}


	public void setUploadFilePath(String uploadFilePath) {
		this.uploadFilePath = uploadFilePath;
	}


	public String getDivHight() {
		return divHight;
	}


	public void setDivHight(String divHight) {
		this.divHight = divHight;
	}


}
